// pages/overhaul/overhaul.js
const app = getApp();
import CommonService from '../../utils/service/commonService.js';
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../utils/util');
import Base64 from '../../utils/Base64.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参来的设备信息
    equipmentInfo:null,    
    //列表
    list:[],
    //页码
    page: 1,
    //是否无更多
    notMore: true,
    //无数据
    showNothing:false,
    //用户权限
    authority:null,
    //是否查单个设备的记录
    isOne:false,
    //搜索关键词
    searchValue:'',
    //需要搜索的设备id
    searchIds:[],
    //是否搜索
    isSearchId:false,
    //售后人员
    staffMap: new Map()
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({	        
      authority:app.globalData.authority
    });

    if(options.paramObj){
      this.setData({ 
        equipmentInfo: JSON.parse(options.paramObj),
        isOne:true         
      })                     
    }
    
    //查询售后人员
    this.getStaffList();
  },

  //获取列表数据
  getList(){
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '加载中...'
    });

    let param = {
      isAuth: true,
      className: 'afterSaleOverhaul',
      data: {
        selectFields: ['id','departId','depart','overhaulPersonnel','service','overhaulDate','partMoney','serviceMoney','logisticsMoney','pic','equipmentState','remark','result','equipmentObj'],
        sort: {
          overhaulDate: -1
        },
        page: {
          page: this.data.page,
          pageSize: 10
        }
      }
    }

    //按平台查询记录
    let appId=app.globalData.myAppId;
    if(appId!=3){
      if(app.globalData.afterSaleSelf){
        //是否独立售后
        param.data.appId=app.globalData.myAppId;
      }else{
        param.data.appId=[2,3,null];
      }
    }else{
      param.data.appId=[2,3,null];
    }

    if(this.data.isOne){
      param.data.equipmentId=this.data.equipmentInfo.equipmentId;
      param.data.nbl=Base64.encode(util.timeFormatDay(new Date()));
    }

    //搜索
    if(this.data.isSearchId){
      param.data.equipmentId=this.data.searchIds;
    }

    CommonService.goFindList(param).then(res => {
      Toast.clear();
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result;
        result.forEach(item => {
          //计算费用
          item.self_all=Number(item.partMoney)+Number(item.serviceMoney)+Number(item.logisticsMoney);
          
          //处理图片
          if(item.pic && item.pic!='null'){
            item.pic=JSON.parse(item.pic);              
          }
          
          //处理日期
          if(item.overhaulDate){
            item.overhaulDate=util.timeFormat(item.overhaulDate);
          }

          //检修人员和电话
          if(item.overhaulPersonnel){            
            let maps=this.data.staffMap;
            if(maps.get(item.overhaulPersonnel)){
              item.self_staffName=maps.get(item.overhaulPersonnel).name;
              item.self_staffPhone=maps.get(item.overhaulPersonnel).phone;
            }            
          }
        });

        console.log('检修列表');
        console.log(result);

        this.setData({
          list: this.data.list.concat(result)
        })
      }else{
        this.setData({
          notMore: false
        })
        if(this.data.page==1){
          this.setData({
            showNothing: true
          })
        }else{
          Toast.fail('没有更多了');
        }
      }
    }).catch((error) => {
      this.setData({
        showNothing: true
      })
    })
  },  

  //刷新列表和页码
  refreshListAndPage(){
    this.setData({ 
      list: [],
      page:1,
      notMore: true,
      showNothing: false
    })
    this.getList();
  },  

  //跳转添加
  goToAdd(){
    wx.navigateTo({
			url: "/pages/overhaulAdd/overhaulAdd?paramObj="+JSON.stringify(this.data.equipmentInfo)
		})
  },

  //跳转编辑
  goToEdit(e){
    let detail=e.currentTarget.dataset.detail;
    wx.navigateTo({
			url: "/pages/overhaulAdd/overhaulAdd?id="+detail.id+"&paramObj="+JSON.stringify(this.data.equipmentInfo)
		})
  },

  //跳转详情
  goToDetail(e){
    let detail=e.currentTarget.dataset.detail;
    wx.navigateTo({
			url: "/pages/overhaulDetail/overhaulDetail?id="+detail.id
		})
  },
  
  //预览图片
  onPreviewImage(e) {
    let detail = e.target.dataset.detail;    
    let src = e.target.dataset.src;    

    let newArr=[];
    for(let i=0;i<detail.length;i++){
      newArr.push(detail[i].url);
    }    

    wx.previewImage({
      current: src,
      urls: newArr
    })
  },

  //获取搜索词
  onChangeSearch(e) {
    this.setData({
      searchValue: e.detail,
    })
  },

  //点击搜索
  onSearch(){
    if(this.data.searchValue){
      //先查出设备id再查检修记录
      let param = {
        searchKey: this.data.searchValue,
        selectFields:["id"]
      }
      
      CommonService.goFindEquipmentList(param).then(res=>{
        let arr=[];
        if(res.data.data && res.data.data.result && res.data.data.result.length){
          let result=res.data.data.result;
          result.forEach(item => {
            arr.push(item.id);
          });
        }
        this.setData({
          isSearchId:true,
          searchIds: arr
        })
        this.refreshListAndPage();

      }).catch((error) => {
      })
    }else{
      this.setData({
        isSearchId:false
      })
      this.refreshListAndPage();
    }
  },

  //查询售后人员
  getStaffList(){
    let param = {
      isAuth: false,
      className: 'servicePersonal',
      data: {
        searchAll: true,
        selectFields: ['id','serviceName','telephone'],
        nbl:Base64.encode(util.timeFormatDay(new Date()))
      }
    }

    //按平台查询记录
    let appId=app.globalData.myAppId;
    if(appId!=3){
      if(app.globalData.afterSaleSelf){
        //是否独立售后
        param.data.appId=app.globalData.myAppId;
      }else{
        param.data.appId=[2,3,null];
      }
    }else{
      param.data.appId=[2,3,null];
    }  

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;

        let map=new Map();
        result.forEach(item => {
          map.set(
            item.id,
            {
              name: item.serviceName,
              phone: item.telephone
            }
          );
        });

        console.log('售后人员');
        console.log(map);

        this.setData({
          staffMap: map
        }) 
        
        //获取列表数据
        this.getList();
      }
    }).catch((error) => {
    })
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.notMore){
      this.setData({ 
        page: this.data.page + 1 
      })      
      this.getList();      
    }
  }  
})